package org.linlinjava.litemall.db.service;

import org.linlinjava.litemall.db.dao.LitemallSecurityConfigMapper;
import org.linlinjava.litemall.db.dao.LitemallSecurityConfigExample;
import org.linlinjava.litemall.db.domain.LitemallSecurityConfig;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class LitemallSecurityConfigService {
    @Resource
    private LitemallSecurityConfigMapper securityConfigMapper;

    public LitemallSecurityConfig findById(Integer id) {
        return securityConfigMapper.selectByPrimaryKey(id);
    }

    public LitemallSecurityConfig findDefault() {
        LitemallSecurityConfigExample example = new LitemallSecurityConfigExample();
        example.or().andDeletedEqualTo(false);
        example.setOrderByClause("id asc");
        List<LitemallSecurityConfig> configs = securityConfigMapper.selectByExample(example);
        if (configs.isEmpty()) {
            return createDefaultConfig();
        }
        return configs.get(0);
    }

    private LitemallSecurityConfig createDefaultConfig() {
        LitemallSecurityConfig config = new LitemallSecurityConfig();
        config.setEnableAccessControl(false);
        config.setAllowedIpRange("");
        config.setMaxConcurrentAccess(100);
        config.setRateLimit(10);
        config.setEnableWatermark(false);
        config.setWatermarkText("");
        config.setAddTime(LocalDateTime.now());
        config.setUpdateTime(LocalDateTime.now());
        config.setDeleted(false);
        securityConfigMapper.insertSelective(config);
        return config;
    }

    public int add(LitemallSecurityConfig config) {
        config.setAddTime(LocalDateTime.now());
        config.setUpdateTime(LocalDateTime.now());
        config.setDeleted(false);
        return securityConfigMapper.insertSelective(config);
    }

    public int updateById(LitemallSecurityConfig config) {
        config.setUpdateTime(LocalDateTime.now());
        return securityConfigMapper.updateByPrimaryKeySelective(config);
    }

    public void deleteById(Integer id) {
        securityConfigMapper.logicalDeleteByPrimaryKey(id);
    }

    public int saveOrUpdate(LitemallSecurityConfig config) {
        if (config.getId() == null) {
            // 检查是否已存在配置，如果存在则更新，否则创建
            LitemallSecurityConfig existing = findDefault();
            if (existing != null && existing.getId() != null) {
                config.setId(existing.getId());
                return updateById(config);
            } else {
                return add(config);
            }
        } else {
            return updateById(config);
        }
    }
}